package com.gitee.fdc.adminui.demo.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gitee.fdc.adminui.demo.domain.DemoSingleTable;
import com.gitee.fdc.adminui.demo.domain.DemoSingleTableSVO;
import com.gitee.fdc.adminui.demo.service.IDemoSingleTableService;
import com.gitee.fdc.web.ajax.Result;
import com.gitee.fdc.web.ajax.ResultGenerator;
import com.gitee.fdc.web.page.PageInfoBT;
import com.gitee.fdc.web.page.PageKit;
import com.gitee.fdc.web.page.PageReq;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilder;
//import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import com.gitee.fdc.adminui.demo.dao.DemoSingleTableEsDao;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

/**
 * 单样例 信息操作处理
 *
 * @author Mr.fdc
 * @date 2019-05-20T08:56:53.535+08:00
 */
@Slf4j
@Controller
@RequestMapping("/singleTable")
public class DemoSingleTableController {

    private String prefix = "singleTable";

    @Autowired
    private IDemoSingleTableService demoSingleTableService;

    @GetMapping()
    public String demoSingleTable() {
        return prefix + "/demoSingleTable";
    }

    /**
     * 查询单样例列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public PageInfoBT list(DemoSingleTableSVO demoSingleTable) {
//        startPage();
        List<DemoSingleTable> list = demoSingleTableService.selectDemoSingleTableList(demoSingleTable);
        return new PageInfoBT(list);
    }
//    @Autowired
//    private RestHighLevelClient client;
    @Autowired(required = false)
    private DemoSingleTableEsDao esdao;
    private String index = "demo_single_table";

    /**
     * @Ref：https://blog.51cto.com/12173069/2285608
     * @Ref：https://blog.csdn.net/sweeper_freedoman/article/details/82847754
     */
    @RequestMapping("/fullTextList")
    @ResponseBody
    public PageInfoBT fullTextList(@RequestParam(name = "keyWords", required = false) String keyWords) {

        Page<DemoSingleTable> p = this.matchPhraseQuery(keyWords);
        PageInfoBT pt = new PageInfoBT();
        pt.setTotal(p.getTotalElements());
        pt.setRows(p.getContent());
        return pt;
    }

    public Page<DemoSingleTable> matchPhraseQuery(String query) {
        PageReq pr = PageKit.getPageReqs();
//        sb.query(QueryBuilders.matchPhraseQuery("varcharField", query));
//        QueryBuilder sb = QueryBuilders.matchPhraseQuery("varcharField", query);
//
//        return (Page<DemoSingleTable>) esdao.search(sb, PageRequest.of(pr.getPage(), pr.getLimit()));
        Sort s = null;
        if (pr.getSort() != null) {
            s = Sort.by(pr.getSort());
            if (pr.isAsc()) {
                s.ascending();
            } else {
                s.descending();
            }
        }
        QueryBuilder qb = null;
        if (!query.isEmpty()) {
            qb = QueryBuilders.matchPhraseQuery("varcharField", query);
            return esdao.search(qb, PageRequest.of(pr.getPage(), pr.getLimit(), s));
        } else {
            return esdao.findAll(PageRequest.of(pr.getPage(), pr.getLimit(), s));
        }

    }
//    public void search(String index, String name) throws IOException {
//        PageReq pr = PageKit.getPageReqs();
//        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
////        boolBuilder.must(QueryBuilders.matchQuery("name", name)); // 这里可以根据字段进行搜索，must表示符合条件的，相反的mustnot表示不符合条件的
//        // boolBuilder.must(QueryBuilders.matchQuery("id", tests.getId().toString()));
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.query(QueryBuilders.matchAllQuery());
////        sourceBuilder.query(boolBuilder);
//        sourceBuilder.from(pr.getOffset());
//        sourceBuilder.size(pr.getLimit()); // 获取记录数，默认10
//        sourceBuilder.fetchSource(new String[]{"id", "varchar_field","int_field"}, new String[]{}); // 第一个是获取字段，第二个是过滤的字段，默认获取全部
//        SearchRequest searchRequest = new SearchRequest(index);
////        searchRequest.types(type);
//        searchRequest.source(sourceBuilder);
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//        System.out.println("search: " + response.toString());
//        SearchHits hits = response.getHits();
//        SearchHit[] searchHits = hits.getHits();
//        for (SearchHit hit : searchHits) {
//            System.out.println("search -> " + hit.getSourceAsString());
//        }
//    }

    /**
     * 新增单样例
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        DemoSingleTable demoSingleTable = new DemoSingleTable();
        mmap.put("demoSingle", demoSingleTable);
        return prefix + "/form";
    }

    /**
     * 新增保存单样例
     *
     * @param demoSingleTable
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Result addSave(DemoSingleTable demoSingleTable) {
        int rs = demoSingleTableService.save(demoSingleTable);
        Result rt = rs > 0 ? ResultGenerator.genSuccessResult() : ResultGenerator.genFailResult("保存失败");
        return rt;
    }

    /**
     * 修改单样例
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        DemoSingleTable demoSingleTable = demoSingleTableService.findById(id);
        mmap.put("demoSingle", demoSingleTable);
        return prefix + "/form";
    }

    /**
     * 修改保存单样例
     */
    @PostMapping("/edit")
    @ResponseBody
    public Result editSave(DemoSingleTable demoSingleTable) {
        int rs = demoSingleTableService.save(demoSingleTable);
        return rs > 0 ? ResultGenerator.genSuccessResult() : ResultGenerator.genFailResult("保存失败");
    }

    /**
     * 删除单样例
     */
    @PostMapping("/delete")
    @ResponseBody
    public Result remove(@RequestParam String ids) {
        int rs = demoSingleTableService.deleteByIds(ids);
        return rs > 0 ? ResultGenerator.genSuccessResult() : ResultGenerator.genFailResult("删除失败");
    }

    /**
     * 恢复单样例
     */
    @PostMapping("/undelete")
    @ResponseBody
    public Result unDelete(@RequestParam Long id) {
        int rs = demoSingleTableService.unDeleteById(id);
        return rs > 0 ? ResultGenerator.genSuccessResult() : ResultGenerator.genFailResult("恢复失败");
    }
}
